<template>
  <md-popup id="popup-container" v-model="value" position="bottom" :has-mask="true" prevent-scroll @hide="cancel">
    <md-popup-title-bar title="选择出发时间" :ok-text="okStr" :cancel-text="cancelStr" @confirm="confirm" @cancel="cancel"></md-popup-title-bar>
    <div ref="slider" class="slider">
      <div class="container">
        <div class="hint">
          <img class="hint-icon" :src="require('@/assets/imgs/tk_ts.png')" style="margin-right:5px;" />
          <div>
            <p v-html="getOrderTimeMsg"></p>
          </div>
          <!-- <div v-if="getPinStartTimeConfig&&getPinStartTimeConfig.type!='2'">
                        本线路服务时间为
                        <span class="theme-str">{{timeString}}</span>，请提前
                        <span class="theme-str">{{getPinStartTimeConfig.preTime}}分钟</span>下单
                    </div>
          <div v-if="getPinStartTimeConfig&&getPinStartTimeConfig.type=='2'">本线路仅以下时间提供拼车服务</div>-->
        </div>
        <md-picker
          ref="picker"
          :data="getOrderTime"
          :cols="2"
          :default-index="pickerDefaultIndex"
          is-view
          is-cascade
          @change="onPickerConfirm"
          @initialed="pickerInited"
        ></md-picker>
      </div>
      <div class="container">
        <div class="flex-box">
          <div class="waiting-hint">
            <img class="hint-icon" :src="require('@/assets/imgs/tk_ts.png')" />
            <div class="waiting-hint" v-if="carFlag=='0'">
              已选择
              <span class="hint-str">{{confirmed.timeStr}}</span>，该时间车辆少，会影响您的正常出行，您可重新选择有车的时间段
            </div>
            <div class="waiting-hint" v-if="carFlag=='1'">
              已选择
              <span class="hint-str">{{confirmed.timeStr}}</span>，请选择可等待的时长
            </div>
          </div>
        </div>
        <md-picker
          ref="waitingPicker"
          :data="waitingTimeList"
          :cols="1"
          :default-index="[0]"
          is-view
          @change="onWaitingPickerConfirm"
          @initialed="waitingPickerInited"
        ></md-picker>
      </div>
    </div>
  </md-popup>
</template>

<script>
/**
 * 此组件为两步时间选择的组件，用于1.7.1+版本的拼车时间选择
 * 此组件根据服务器返回的时间显示日期以及时间，并标注是否有车
 * 之后选择愿意等待的时间
 */
import { Popup, PopupTitleBar, Picker, Dialog } from 'mand-mobile';
import { mapGetters } from 'vuex';
import { GET_ORDER_TIME } from '@/store/actions.types';
import { PIN_CONFIRM_ORDER_TIME } from '@/store/mutations.types';
import Loading from '@/components/loading';
import http from '@/common/http';
var moment = require('moment');
moment.locale('zh-cn');
export default {
  name: 'time-selector',
  components: {
    [Popup.name]: Popup,
    [PopupTitleBar.name]: PopupTitleBar,
    [Picker.name]: Picker
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    appendTo: {
      default: () => document.body
    }
  },
  data() {
    return {
      titleStr: '选择出发时间',
      cancelStr: '取消',
      okStr: '下一步',
      pickerData: [],
      pickerDefaultIndex: [0, 0],
      step: 1,
      carFlag: '0',
      confirmed: {
        timeStr: '', // 时间字符串
        time: null, // moment对象
        wait: 0, // 等待分钟
        endTime: null
      },
      waitingTimeList: [[]]
    };
  },
  created() {
    if (this.getPinStartTimeConfig.type === '2') {
      this.titleStr = '选择出发时间';
      this.cancelStr = '取消';
      this.okStr = '确认';
    }
  },
  methods: {
    confirm() {
      if (this.getPinStartTimeConfig.type === '2') {
        this.commitData();
        this.value = false;
        this.$emit('submit');
        return;
      }
      if (this.step === 1) {
        if (this.confirmed.time) {
          this.step = 2;
          this.stepTwo();
        } else {
          Dialog.alert({
            title: '错误',
            content: '请选择正确的时间'
          });
        }
      } else if (this.step === 2) {
        this.commitData();
        this.value = false;
        this.$emit('submit');
      }
    },
    commitData() {
      this.confirmed.endTime = moment(this.confirmed.time).add(this.confirmed.wait, 'm');
      this.$store.commit(PIN_CONFIRM_ORDER_TIME, this.confirmed);
    },
    stepOne() {
      this.titleStr = '选择出发时间';
      this.cancelStr = '取消';
      this.okStr = '下一步';
      this.$refs.slider.style.transform = 'translate3d(0vw,0px,0)';
    },
    stepTwo() {
      this.waitingTimeList = [[]];
      this.titleStr = '我愿意等待';
      this.cancelStr = '上一步';
      this.okStr = '确认';
      this.$refs.slider.style.transform = 'translate3d(-100vw,0px,0)';
      let params = {
        route_id: this.getRoute.route_id,
        time: this.confirmed.time._i.toString()
      };
      Loading.show();
      http.post('/pakj/route/getWaitTime', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          for (let i in res.data.data) {
            let obj = {
              text: res.data.data[i].text + '分钟',
              value: res.data.data[i].text
            };
            this.waitingTimeList[0].push(obj);
            this.waitingPickerInited();
          }
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
      // this.getWaitingOrderTime[0].forEach((item, index) => {
      //     let time = moment(this.confirmed.time).add(item.value, 'm');
      //     if (time.isBefore(this.endMoment) || time.isSame(this.endMoment)) {
      //         this.waitingTimeList[0].push(item);
      //         this.waitingPickerInited();
      //     }
      // });
    },
    cancel() {
      if (this.step === 1) {
        this.value = false;
        this.$emit('cancel');
      } else if (this.step === 2) {
        this.step = 1;
        this.stepOne();
      }
    },
    pickerInited() {
      this.$refs.picker.refresh(() => {
        this.getPickerValueByIndexs();
      });
    },
    waitingPickerInited() {
      this.$refs.waitingPicker.refresh(() => {
        if (this.$refs.waitingPicker.getColumnValues()) {
          if (this.$refs.waitingPicker.getColumnValues().length > 0) {
            if (this.$refs.waitingPicker.getColumnValues()[0]) {
              this.confirmed.wait = this.$refs.waitingPicker.getColumnValues()[0].value;
            }
          }
        }
      });
    },
    onPickerConfirm(columnIndex, itemIndex, value) {
      this.getPickerValueByIndexs();
    },
    onWaitingPickerConfirm(columnIndex, itemIndex, value) {
      if (value) {
        this.confirmed.wait = value.value;
      }
    },
    getPickerValueByIndexs() {
      let pickerIndexs = this.$refs.picker.getColumnIndexs();
      if (this.getOrderTime[0].length > 0) {
        let obj = this.getOrderTime[0][pickerIndexs[0]];
        if (!obj) {
          return;
        }
        if (obj.children.length > 0) {
          let timeNumber = parseInt(obj.children[pickerIndexs[1]].value);
          this.confirmed.time = moment(timeNumber);
          this.confirmed.timeStr = this.confirmed.time.calendar(null, {
            sameDay: '[今天] HH:mm',
            nextDay: '[明天] HH:mm',
            nextWeek: 'MMMDodddd HH:mm',
            lastDay: '[昨天] HH:mm',
            lastWeek: 'MMMDodddd HH:mm',
            sameElse: 'MMMDodddd HH:mm'
          });
          this.carFlag = obj.children[pickerIndexs[1]].car_flag;
        } else {
          this.confirmed.time = null;
        }
      }
    }
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  computed: {
    ...mapGetters(['getOrderTime', 'getPinStartTimeConfig', 'getWaitingOrderTime', 'getOrderTimeMsg', 'getRoute']),
    timeString() {
      let config = this.getPinStartTimeConfig;
      if (!config) {
        return '';
      }
      let startMoment = moment()
        .hours(config.start.split(':')[0])
        .minutes(config.start.split(':')[1])
        .seconds(0);
      let endMoment = moment()
        .hours(config.end.split(':')[0])
        .minutes(config.end.split(':')[1])
        .seconds(0);
      let startTime = startMoment.format('AHH:mm');
      let endTime = endMoment.subtract(30, 'minute').format('AHH:mm');
      return startTime + '~' + endTime;
    },
    endMoment() {
      let config = this.getPinStartTimeConfig;
      if (!config) {
        return '';
      }
      let mom = moment(this.confirmed.time)
        .hours(config.end.split(':')[0])
        .minutes(config.end.split(':')[1])
        .seconds(0);
      return mom;
    }
  }
};
</script>

<style lang="stylus">
#popup-container {
  .slider {
    width: 200vw;
    transform: translate3d(0, 0, 0);
    transition: transform 0.5s ease-in-out;

    .container {
      background-color: #fff;
      height: 432px;
      width: 100vw;
      float: left;
      font-size: 22px;

      .hint {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        font-size: 22px;
        color: color-text-caption;

        .hint-icon {
          width: 26px;
          height: 24px;
        }

        .theme-str {
          color: theme-color;
        }
      }

      .hint_s {
        font-size: 22px;
        color: color-text-caption;

        .hint-icon {
          position: absolute;
          top: 25px;
          left: 50px;
          width: 26px;
          height: 24px;
        }

        .hint_s_box {
          margin: 10px 30px 0px 30px;
        }

        .hint_s_box p {
          text-align: center;
        }
      }

      .flex-box {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88px;

        .waiting-hint {
          display: -webkit-box;
          font-size: 22px;

          .hint-icon {
            width: 26px;
            height: 24px;
          }

          .hint-str {
            color: theme-color;
          }

          .waiting-hint {
            color: color-text-caption;
            max-width: 25em;
            text-align: center;
          }
        }
      }
    }
  }
}
</style>
